package gov.nasa.anml.lifted;

import java.util.ArrayList;
import java.util.HashMap;

import gov.nasa.anml.utility.SimpleString;


public class SymbolTable<T extends Identifier<?, ?>> {
	public int count = 0;
	public ArrayList<T> table = new ArrayList<T>();
	public HashMap<SimpleString,T> map = new HashMap<SimpleString,T>();

	public SymbolTable() {
	}

	public SymbolTable(T s) {
		put(s);
	}

	public <S extends T> S put(S s) {
		SimpleString v = s.name();
		T o = map.get(v);
		if (o != null) {
			return (S) o;
		}
		map.put(v, s);
		table.add(s);
		s.id(count++);
		return s;
	}
	
	// if this is done in the wrong order there will be id collisions (maybe)
	// with later declared symbols, and table[id] won't map to the symbol
	// with that id.  But one can still iterate over the table to get all the symbols
	// and count is still the number of symbols, so one can use other integer spaces
	// for inherited ids if that is useful (like negative numbers, avoiding id collisions)
	public void inherit(T s) {
		map.put(s.name(),s);
		table.add(s);
		++count;
	}
	
	public void inherit(SymbolTable<T> s) {
		for (T t : s.table) {
			map.put(t.name(),t);
			table.add(t);
		}
		count += s.count;
	}

	public T get(SimpleString k) {
		T r = map.get(k);
		return r;
	}

	public T get(int i) {
		return table.get(i);
	}

	public SimpleString getName(int i) {
		return table.get(i).name();
	}

	public String toString() {
		return table.toString();
	}
}
